package com.lian.community.controller.post;

import com.lian.community.constant.ResponseCode;
import com.lian.community.constant.TextType;
import com.lian.community.entity.post.Post;
import com.lian.community.entity.user.HostUser;
import com.lian.community.entity.user.User;
import com.lian.community.service.post.PostService;
import com.lian.community.service.text.SensitiveService;
import com.lian.community.service.text.TextFilterService;
import com.lian.community.service.token.TokenService;
import com.lian.community.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

@Controller
public class PostController {
    @Autowired
    PostService postService;
    @Autowired
    SensitiveService sensitiveService;
    @Autowired
    TextFilterService textFilterService;
    @Autowired
    TokenService tokenService;
    @Autowired
    HostUser hostUser;
    @Value("${contentLength}")
    int contentLength;
    @Value("${titleLength}")
    int titleLength;



    @RequestMapping(value = "/getPost/{postId}")
    public String getPost(Model model, @PathVariable("postId")int id){
        Post post = postService.getPost(id);
        if(post == null){
            return "error";
        }
        model.addAttribute("title", post.getTitle());
        model.addAttribute("content", post.getContent());

        return "showPost";
    }

    @RequestMapping(value = "/toPost")
    public String toPost(){
        return "post";
    }

    @RequestMapping(value = "/addPost")
    public String addPost(Post post){
        Map<String,Object> map = hostUser.getValue();
        User user = (User)map.get("user");
        Integer userId = user.getId();
        if(!post.createValid(contentLength, titleLength)){
            return JsonUtil.getJsonString(ResponseCode.PARAM_ILLEGAL, "参数错误！");
        }

        try {
            String content = textFilterService.getFilterString(post.getContent(), TextType.POST_CONTENT);
            String title = textFilterService.getFilterString(post.getTitle(), TextType.POST_TITLE);
            if(content == null || title == null){
                return JsonUtil.getJsonString(ResponseCode.PARAM_ILLEGAL, "参数错误！");
            }
            post.setContent(sensitiveService.getFilter(content));
            post.setTitle(sensitiveService.getFilter(title));
            postService.addPost(post, userId);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonUtil.getJsonString(ResponseCode.SERVER_ERROR, "服务出错！");
        }
        return JsonUtil.getJsonString(ResponseCode.REQUEST_SUCCEED, "操作成功！");
    }
}
